package org.epidroid.epidroid.news.ui;

import java.util.Collections;
import java.util.List;

import org.epidroid.epidroid.R;
import org.epidroid.epidroid.androsoul.engine.AndroSoul;
import org.epidroid.epidroid.news.engine.Group;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

public class NewsAdapter extends ArrayAdapter<Group> {

	private List<Group> _items = null;
	private NewsActivity _context = null;

	public void setItems(List<Group> items) {
		_items = items;
		Collections.sort(_items);
	}

	public NewsAdapter(NewsActivity context, int textViewResourceId,
			List<Group> objects) {
		super(context, textViewResourceId, objects);

		setItems(objects);
		_context = context;
	}

	@Override
	public int getCount() {
		return _items.size();
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		View v = convertView;
		ViewHolder holder;
		/*
		 * TODO if the layout is not recreated, the oncheckchange listener is
		 * always called for the checkbox, which causes problems. So, we force
		 * the inflation of the layout here (not optimized... until we find a
		 * solution.
		 */
		if (v == null) {
			holder = new ViewHolder();
			LayoutInflater inflater = (LayoutInflater) _context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = inflater.inflate(R.layout.news_item, null);
			holder.box = (CheckBox) v.findViewById(R.id.news_item_fav_button);
			holder.text = (TextView) v.findViewById(R.id.news_item_title);
			v.setTag(holder);
		  }
		  else{
			  // Get the ViewHolder back to get fast access 
	          // to the TextView and the ImageView
			  holder = (ViewHolder) convertView.getTag();
		  }
		final Group g = this._items.get(position);
		//final NewsgroupInfo m = g.getInfo();

		holder.text.setText(g.getTitle() + " (" + g.getCount() + ")");

		holder.text.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				NewsAdapter.this._context.onListItemClick(g);
			}
		});



		holder.box.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				g.setFav(isChecked);
				Log.d(AndroSoul.LOGCAT, g.getTitle() + " is now "
						+ isChecked + " - pos = " + position);
			}
		});
		holder.box.setChecked(g.isFav());
		return (v);
	}
	
	private class ViewHolder {
		CheckBox box;
		TextView text;
	}
}
